<?php

// 应用公共文件
/**
 * 发送http GET请求
 *
 * @param string $url get请求地址
 * @param int $httpCode 返回状态码
 * @return mixed
 */
function http_get($url, &$httpCode = 0){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}

/**
 * 发送http POST请求
 *
 * @param string $url 请求地址
 * @param array $params 请求参数
 * @return mixed
 */
function http_post($url, array $params = array()){
    $data_string = json_encode($params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt(
        $ch, CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json'
        )
    );
    $data = curl_exec($ch);
    curl_close($ch);
    return ($data);
}

/**
 * 获取随机字符
 *
 * @param int $length
 * @return string
 */
function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0;
         $i < $length;
         $i++) {
        $str .= $strPol[rand(0, $max)];
    }

    return $str;
}


/**
 * 数组根据某字段排序
 *
 * @param array $list 二维数组
 * @param string $field 依据字段
 * @param boolean $asc 默认升序
 * @return array
 */
function listSort(array $list, string $field,$asc = true){
    if ($asc) {
        array_multisort(array_column($list,$field),SORT_ASC,$list);
    }else{
        array_multisort(array_column($list,$field),SORT_DESC,$list);
    }
    return $list;
}

/**
 * 从二维数组总查找某字段
 *
 * @param array $array
 * @param string $fleid
 * @param mixed $find
 * @return array|false
 */
function fInArray($array,$fleid,$find){
    foreach ($array as $key => $v) {
        if($v[$fleid] == $find) return $v;
    }
    return false;
}

/**
     * 生成全局id
     *
     * @return void
     */
function unID(){
    $startYear = 2018;
    $yCode = ['A','B','C','D','E','F','G','H','I','J','K','L','M'];
    $order_sn = '' 
        .$yCode[intval(date('Y')-$startYear)]   // 年(1)
        .\dechex(date('m'))                     // 月(1)
        .date('d')                              // 日(2)
        .sprintf('%02s',dechex(\rand(0,255)))  // 00-ff随机数(2)
        .\substr(\microtime(),2,5)              // 毫秒(5)
        .\substr(time(),-5)                     // 秒(5)
    ;
    return $order_sn;
}